import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sk.z
 * 阿里面试的一道笔试题,当时要求时间有限,花了半小时.
 * 虽然有很多可以优化的地方,但还是想着保留原始状态.
 * 题目:三线程轮询打印从1-75,轮到线程打印递增5次,然后交给下个线程.
 */
public class PollingPrint {

    private static AtomicInteger count;
    private static AtomicInteger who;

    public static void main(String[] args) {
        count = new AtomicInteger(1);
        who = new AtomicInteger(1);

        PrintThread pt1 = new PrintThread(1, count, who);
        PrintThread pt2 = new PrintThread(2, count, who);
        PrintThread pt3 = new PrintThread(3, count, who);

        new Thread(pt1).start();
        new Thread(pt2).start();
        new Thread(pt3).start();

    }


    private static class PrintThread implements Runnable {

        private final AtomicInteger count;
        private final AtomicInteger whoTurn;
        private final Integer my;

        PrintThread(Integer my, AtomicInteger count, AtomicInteger whoTurn) {
            this.my = my;
            this.count = count;
            this.whoTurn = whoTurn;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (count) {
                    if (count.get() >= 75) {
                        break;
                    }
                    if (my.equals(whoTurn.get())) {
                        if (whoTurn.getAndIncrement() >= 3) {
                            whoTurn.set(1);
                        }
                        for (int i = 0; i < 5; i++) {
                            System.out.println(Thread.currentThread() + " " + count.getAndIncrement());
                        }
                        count.notifyAll();
                    } else {
                        try {
                            System.out.println(Thread.currentThread() + "I am " + my + ", now is turn" + whoTurn);
                            count.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            System.out.println(Thread.currentThread() + " game over;");
        }
    }

}
